/**********************************************************************************
 * Copyright (c) 2012 - 2012,  quick_tools, All right reserved
 * Title: com.adc.quicktools  ListComparator.java 
 * @author shen  shenqiao2012@163.com 
 *  2012-7-17 上午11:28:45 
 *********************************************************************************/

package com.adc.quicktools;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Comparator;

@SuppressWarnings("rawtypes")
public class ListComparator implements Comparator {

	public ListComparator() {
	}

	public ListComparator(String methodName) {
		this.methodName = methodName;
	}

	// 空:普通的数据类型 非空:对象数据类型 取methodName返回值比较
	private String methodName;

	/**
	 * Description:
	 * 
	 * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
	 */
	@Override
	public int compare(Object obj1, Object obj2) {
		int val = -1;
		try {
			if (methodName == null) {
				val = _compare(obj1, obj2);
			} else {
				val = _compare(ObjectUtil.getter(obj1, methodName), ObjectUtil.getter(obj2, methodName));
			}
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return val;
	}

	/**
	 * 
	 * Description: 对两个对象进行比较;
	 * author: shen
	 * 
	 * @param obj1
	 * @param obj2
	 * @throws Exception
	 * @return int
	 * @throws NoSuchMethodException
	 * @throws SecurityException
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 */
	public int _compare(Object obj1, Object obj2) throws SecurityException, NoSuchMethodException,
			IllegalArgumentException, IllegalAccessException, InvocationTargetException {
		if (obj1 == null || obj2 == null)
			return obj1 == null ? -1 : 1;
		Class cl = obj1.getClass();
		if (obj1 instanceof java.lang.Comparable) {
			// byte int long float..number, date , boolean , char
			Method getMethod = obj1.getClass().getMethod("compareTo", new Class[] { cl });
			return (Integer) getMethod.invoke(obj1, new Object[] { obj2 });
		}
		return -1;
	}

}
